package com.stu.boke.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.stu.boke.entity.Category;
import com.stu.boke.mapper.ArticleCategoryRefMapper;
import com.stu.boke.mapper.CategoryMapper;
import com.stu.boke.service.CategoryService;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {
	
	@Autowired(required = false)
	private CategoryMapper categoryMapper;
	
	@Autowired(required = false) 
	private ArticleCategoryRefMapper articleCategoryRefMapper;

	@Override
	public List<Category> listCategory() {
		return categoryMapper.listCategory();
	}

	@Override
	public Integer countCategory() {
		return categoryMapper.countCategory();
	}

	@Override
	public List<Category> listCategoryWithCount() {
		List<Category> categoryList = null;
		try {
			categoryList = categoryMapper.listCategory();
			for (int i = 0; i < categoryList.size(); i++) {
				Integer count = articleCategoryRefMapper.countArticleByCategoryId(categoryList.get(i).getCategoryId());
				categoryList.get(i).setArticleCount(count);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("根据文章获得分类列表失败,cause:{}",e);
		}
		return categoryList;
	}

	@Override
	public Category insertSubmitCategory(Category category) {
		try {
			categoryMapper.insert(category);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("创建分类失败, category:{}, cause:{}", category, e);
		}
		return category;
	}

	@Override
	public Category getCategoryById(Integer id) {
		return categoryMapper.getCategoryById(id);
	}

	@Override
	public void updateCategory(Category category) {
		try {
			categoryMapper.update(category);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("更新分类失败, category:{}, cause:{}", category, e);
		}
	}

	@Override
	public void deleteCategory(Integer id) {
		try {
			categoryMapper.deleteCategory(id);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("删除分类失败, category:{}, cause:{}",  e);
		}
	}

}
